<template>
    <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        :hide-required-asterisk="true"
        :label-width="totalLength"
        :class="row ? `grid-${gridFormItem}` : ''"
        style="width: 100%"
    >
        <el-form-item
            v-for="item in formList"
            :key="item.id"
            :prop="item.prop"
            :size="size"
            :class="`${color}`"
        >
            <template #label v-if="!item.prefix && item.formType !== 'null'">
                <form-label
                    :label="item.label"
                    :asterisk="asterisk"
                    :labelStyle="labelStyle(item)"
                ></form-label>
            </template>
            <el-input
                v-model.trim="formData[item.prop]"
                :placeholder="item.placeholder"
                :suffix-icon="item.suffixIcon"
                :type="item.type"
                v-if="item.formType == 'input'"
            >
                <template #prefix v-if="item.prefix">
                    <div class="fr-ac">
                        <form-label
                            :label="item.label"
                            :asterisk="asterisk"
                            :labelStyle="labelStyle(item)"
                        ></form-label>
                    </div>
                </template>
            </el-input>
            <el-select
                v-model="formData[item.prop]"
                :placeholder="item.placeholder"
                :suffix-icon="item.suffixIcon"
                v-if="item.formType == 'select'"
                @change="selectChange"
            >
                <template #prefix v-if="item.prefix">
                    <div class="fr-ac">
                        <form-label
                            :label="item.label"
                            :asterisk="asterisk"
                            :labelStyle="labelStyle(item)"
                        ></form-label>
                    </div>
                </template>
                <el-option
                    v-for="child in item.list"
                    :key="child.value"
                    :value="child.value"
                    :label="child.label"
                />
            </el-select>
            <el-radio-group
                v-model="formData[item.prop]"
                v-if="item.formType == 'radio'"
            >
                <el-radio
                    v-for="child in item.list"
                    :key="child.value"
                    :value="child.value"
                >
                    {{ child.label }}
                </el-radio>
            </el-radio-group>
            <el-date-picker
                v-if="item.formType == 'date'"
                type="date"
                :placeholder="item.placeholder"
                style="width: 100%"
                v-model="formData[item.prop]"
            />
            <div class="fr-ac-jc flex-1" v-if="item.formType == 'null' && row">
                <el-button
                    v-for="child in item.list"
                    :key="child.value"
                    :style="child.style"
                    :size="size"
                    @click="searchButton(child)"
                >
                    {{ child.label }}
                </el-button>
            </div>
            <div class="flex-1 box" v-if="item.formType == 'box'">
                <el-input
                    v-model="formData[item.prop]"
                    :placeholder="item.placeholder"
                    :suffix-icon="Search"
                    readonly
                    @click="boxClick"
                ></el-input>
                <div class="error">{{ tip }}</div>
            </div>
            <div class="flex-1 fr-ac" v-if="item.formType == 'col'">
                <el-col :span="11">
                    <el-input
                        placeholder="请输入最低分"
                        v-model="formData[`min_${item.prop}`]"
                    />
                </el-col>
                <el-col :span="2" style="text-align: center">
                    <span>-</span>
                </el-col>
                <el-col :span="11">
                    <el-input
                        placeholder="请输入最高分"
                        v-model="formData[`max_${item.prop}`]"
                    />
                </el-col>
            </div>
        </el-form-item>
        <div :style="{ height: height + 'px' }"></div>
        <div
            class="w-100 fr-ac-jc"
            v-if="formButton && !row"
            :class="leftButton && rightButton ? 'px-100' : ''"
        >
            <el-button
                @click="submitForm"
                class="flex-1"
                v-if="leftButton"
                :size="size"
                :style="buttonStyleL"
            >
                {{ buttonTitleL }}
            </el-button>
            <el-button
                @click="resetForm"
                class="flex-1"
                v-if="rightButton"
                :size="size"
                :style="buttonStyleR"
            >
                {{ buttonTitleR }}
            </el-button>
        </div>
    </el-form>
</template>

<script>
import {
    defineComponent,
    nextTick,
    onMounted,
    reactive,
    ref,
    watch,
} from "vue";
import { purpleWhite, purple } from "@/comment/data";
import { Search } from "@element-plus/icons-vue";
export default defineComponent({
    props: {
        // 表单配置
        list: {
            default: () => [
                // {
                //     id: 1,
                //     prefix: true, 是否前置
                //     type: "password", input类型
                //     label: "密码", 表单的label
                //     model:'' 默认值
                //     prop: "password", 字段名
                //     suffixIcon: "", 后缀图标
                //     rules: [], 验证规则
                //     formType: "input", 表单的所需类型 如input、select、null
                //     placeholder: "",
                //     list: [
                //         {
                //             label: "",
                //             value: "",  以下formType为null时写
                //             style: {},
                //             void: (val, ref) => {
                //                 ref.resetFields();
                //             },
                //         },
                //     ],
                // },
            ],
            type: Array, //表单内列表数组
        },
        size: {
            default: "",
            type: String, //表单内组件的尺寸
        },
        asterisk: {
            default: false,
            type: Boolean, //表单内信号位置
        },
        formButton: {
            default: true,
            type: Boolean, //是否展示表单提交、重置按钮
        },
        row: {
            default: false,
            type: Boolean, //表单是否垂直默认为 垂直
        },
        gridFormItem: {
            default: 2,
            type: Number, //水平放几个的数量
        },

        // 表单icon的颜色
        color: {
            default: "purple",
            type: String,
        },

        // 按钮配置
        leftButton: {
            default: true,
            type: Boolean, //表单提交按钮
        },
        rightButton: {
            default: true,
            type: Boolean, //表单重置按钮
        },
        buttonTitleL: {
            default: "确定",
            type: String, //左按钮文字
        },
        buttonTitleR: {
            default: "重置",
            type: String, //右按钮文字
        },
        buttonStyleL: {
            default: () => purple,
            type: Object, //左按钮颜色
        },
        buttonStyleR: {
            default: () => purpleWhite,
            type: Object, //右按钮颜色
        },
        // 表单与按钮间的间距
        height: {
            default: 45,
            type: Number,
        },
        tip: {
            default:
                "选择会员服务系统的会员用户，用于绑定账号、同步系统数据。绑定后不可修改，请谨慎操作!",
            type: String, //提示文字
        },
    },
    emits: ["getFromValue", "selectValue", "box"],
    computed: {},
    methods: {
        labelStyle(val) {
            return {
                color: val.rules.length ? "#f67a75" : "#fff",
            };
        },
        submitForm() {
            this.formRef.validate((valid, fields) => {
                if (valid) {
                    this.$emit("getFromValue", this.formData);
                    console.log("submit!");
                } else {
                    console.log("error submit!");
                }
            });
        },
        resetForm() {
            this.blank()
            if (!this.formRef) return;
            this.formRef.resetFields();
        },
        searchButton(val) {
            switch (val.type) {
                case "query":
                    break;
                case "reset":
                    this.blank()
                    break;
            }
            val.void(this.formData);
        },
        selectChange(val) {
            this.$emit("selectValue", val);
        },
        boxClick() {
            this.$emit("box");
        },
        //model置空
        blank() {
            this.formList.forEach((item) => {
                if (item.prop && item.formType !== "col") {
                    this.formData[item.prop] = item.model || "";
                }
                if (item.prop && item.formType === "col") {
                    this.formData[`max_${item.prop}`] = "";
                    this.formData[`min_${item.prop}`] = "";
                }
            });
        },
    },
    setup(props) {
        const formList = ref([]);
        //model值对象
        const formData = reactive({});
        //验证规则对象
        const formRules = reactive({});
        // 假设每个字符占 14px，计算总长度
        const totalLength = ref(0);
        const formRef = ref(null);
        // 初始化 formData 和 formRules
        watch(
            () => props.list,
            (newList) => {
                //form更新表单数据
                formList.value = newList;
                // 初始化 formData 和 formRules
                newList.forEach((item) => {
                    if (item.rules) {
                        formRules[item.prop] = item.rules; // 使用传入的规则
                    }
                    if (item.prop && item.formType !== "col") {
                        formData[item.prop] = item.model || ""; // 默认值为空字符串
                    }
                    if (item.prop && item.formType === "col") {
                        formData[`max_${item.prop}`] = "";
                        formData[`min_${item.prop}`] = "";
                    }
                });
                console.log(formData, "1111111111111111111111111");
                if (newList.length === 0) return;

                // 正则表达式，用于判断是否全是汉字
                const isAllChinese = (str) => /^[\u4e00-\u9fa5]+$/.test(str);

                const longestLabelObject = newList.reduce(
                    (longest, current) => {
                        // 如果当前对象的label长度更长，更新longest
                        if (current.label.length > longest.label.length) {
                            return current;
                        }
                        // 如果当前对象的label长度与longest相同，检查是否全是汉字
                        if (current.label.length === longest.label.length) {
                            if (
                                isAllChinese(current.label) &&
                                !isAllChinese(longest.label)
                            ) {
                                return current; // 当前对象全汉字且longest不是全汉字，更新longest
                            }
                        }
                        return longest; // 否则，返回原来的longest
                    },
                    newList[0]
                ); // 默认从第一个元素开始
                const valWidth = Array.from(longestLabelObject.label).reduce(
                    (sum, char) => {
                        // 如果是汉字（中文字符），宽度为 14
                        if (/[\u4e00-\u9fa5]/.test(char)) {
                            return sum + 14;
                        }
                        // 其他字符宽度为 8
                        return sum + 10;
                    },
                    0
                );
                totalLength.value = valWidth + 25;
            },
            { deep: true, immediate: true }
        ); // immediate: true 确保在初始化时也会执行一次
        return {
            Search,
            formRef,
            formList,
            formData,
            formRules,
            totalLength,
        };
    },
});
</script>
<style lang="scss" scoped>
.red {
    :deep(.el-input__icon),
    :deep(.el-select__icon) {
        color: red;
    }
}
.purple {
    :deep(.el-input__icon),
    :deep(.el-select__icon) {
        color: #4c3fb1;
    }
}
.error {
    padding-top: 3px;
    line-height: 20px;
    color: red;
}
:deep(.el-form-item__content) {
    margin-left: 0 !important;
}
.box {
    :deep(.el-input.is-disabled .el-input__inner) {
        cursor: default;
    }
    :deep(.el-input.is-disabled .el-input__wrapper) {
        background: #fff;
        cursor: default;
    }
    :deep(.el-input__inner) {
        background: #fff;
        cursor: default;
    }
    :deep(.el-input.is-disabled .el-input__icon) {
        // color: #aaa !important;
        cursor: default;
    }
}
</style>
